package com.njbw.minio.config;

import com.njbw.minio.utils.CustomMinioClient;
import com.njbw.minio.utils.MinioTemplate;
import io.minio.MinioClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({MinioClient.class})
@EnableConfigurationProperties(MinioProperties.class)
public class MinioConfiguration {

    @Bean
    @ConditionalOnMissingBean(CustomMinioClient.class)
    public CustomMinioClient minioClient(MinioProperties minioConfig) {
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(minioConfig.getEndpoint())
                    .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                    .build();
            return new CustomMinioClient(minioClient);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Bean
    @ConditionalOnBean({MinioClient.class})
    @ConditionalOnMissingBean(MinioTemplate.class)
    public MinioTemplate minioTemplate(CustomMinioClient minioClient, MinioProperties minioConfig) {
        return new MinioTemplate(minioClient, minioConfig);
    }
}
